package com.ocp.macro.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ocp.macro.annotation.AutowireUserToken;
import com.ocp.macro.entity.DealerAccount;
import com.ocp.macro.entity.UserInfoToken;
import com.ocp.macro.enums.DataCode;
import com.ocp.macro.exception.MysqlException;
import com.ocp.macro.mapper.dealerAccount.DealerAccountMapper;
import com.ocp.macro.service.OperateService;
import com.ocp.macro.utils.GsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class OperateServiceImpl implements OperateService {
    private final static String CACHE_NAMESPACE = "dealerAccountInfo::";
    private final static Integer[] DEALER_AUTHORITY_ID_ARRAYS = {2,3};
    private final static String DEALER_DEFAULT_PASSWORD = "$2a$10$CwFKceXNpSb.CBejKMWDw.7Zpc9HREBPoH7yPs5BRltHIQzCoQNAq";
    @Resource
    private DealerAccountMapper dealerAccountMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    @AutowireUserToken
    public String getDealerAccountInfoList(DealerAccount dealerAccount, UserInfoToken userInfoToken) {
        PageHelper.startPage(dealerAccount.getPage(), dealerAccount.getRows()); // 分页，设置当前页和每页条数

        dealerAccount.setOptId(userInfoToken.getUserId()); // 设置运营账号id
        dealerAccount.setLogic(1); // 只查询未删除的账号

        String redisKey = CACHE_NAMESPACE+dealerAccount.toString();

        Object object = redisTemplate.opsForValue().get(redisKey);
        if (object!=null){ // 缓存命中
            return (String) object;
        }

        List<DealerAccount> list = dealerAccountMapper.selectDealerAccountList(dealerAccount);
        PageInfo<DealerAccount> pageInfo = new PageInfo <>( list );

        Map<String, Object>  map = new HashMap<>();
        map.put("data", pageInfo.getList()); // 当前页数据
        pageInfo.setList(null);
        map.put("pageInfo", pageInfo); // 分页信息
        map.put("code", DataCode.SUCCESS.getCode());
        map.put("message", DataCode.SUCCESS.getMessage());

        String result = GsonUtils.toJson(map);
        try {
            redisTemplate.opsForValue().set(redisKey, result,6, TimeUnit.MINUTES);//添加缓存
        }catch (Exception e){
            log.error("设置缓存出现异常：{}",e.toString());
        }
        return result;
    }

    @Override
    @AutowireUserToken
    public String createDealerAccountInfo(DealerAccount dealerAccount, UserInfoToken userInfoToken) {
        Map<String, Object> map = new HashMap<>();

        DealerAccount account1 = dealerAccountMapper.selectDealerAccountOne(dealerAccount);
        DealerAccount account2 = dealerAccountMapper.selectDealerAccountOne(dealerAccount);
        if (account1!=null || account2!=null){
            map.put("code", DataCode.ACCOUNT_IS_HAVE.getCode());
            map.put("message", DataCode.ACCOUNT_IS_HAVE.getMessage());
            return GsonUtils.toJson(map);
        }

        dealerAccount.setOptId(userInfoToken.getUserId());
        dealerAccount.setDealPwd(DEALER_DEFAULT_PASSWORD);
        dealerAccount.setCreateDate(new Date());
        dealerAccount.setModifyDate(new Date());

        Integer count = dealerAccountMapper.insertDealerAccount(dealerAccount);
        if (count!=null && count>0){
            count = dealerAccountMapper.insertDealerAccountAuthorities(dealerAccount.getDealAccountId(),
                    Arrays.asList(DEALER_AUTHORITY_ID_ARRAYS)); // 进行授权
            if (count==null || count<=0)
                throw new MysqlException(DataCode.INSERT_EXCEPTION);
        }
        else{
            throw new MysqlException(DataCode.INSERT_EXCEPTION);
        }

        map.put("code", DataCode.SUCCESS.getCode());
        map.put("message", DataCode.SUCCESS.getMessage());

        deleteRedisCache();//清空账号查询相关的缓存

        return GsonUtils.toJson(map);
    }

    @Override
    @AutowireUserToken
    public String deleteDealerAccountInfo(DealerAccount dealerAccount, UserInfoToken userInfoToken) {
        Map<String, Object> map = new HashMap<>();
        // 参数为空
        if (dealerAccount.getList()==null || dealerAccount.getList().size()==0){
            map.put("code", DataCode.PARAM_IS_BLANK.getCode());
            map.put("message", DataCode.PARAM_IS_BLANK.getMessage());
            return GsonUtils.toJson(map);
        }

        dealerAccount.setOptId(userInfoToken.getUserId()); // 只能删除当前运营账号下的经销商总帐号
        List<DealerAccount> accounts = dealerAccountMapper.selectDealerAccountList(dealerAccount);
        Integer count = dealerAccountMapper.deleteDealerAccount(dealerAccount); // 执行删除
        if (count!=null && count>0){
            count = dealerAccountMapper.deleteDealerAccountRelAuthority(dealerAccount);
            if (count==null || count<=0)
                throw new MysqlException(DataCode.DELETE_EXCEPTION);

            if (accounts!=null){
                for (DealerAccount deal: accounts){ // 清空当前redis中登录的账号
                    Set<String> keys = redisTemplate.keys(deal.getUserName() + "*");
                    if (keys!=null)
                        redisTemplate.delete(keys);
                }
            }

        }else{
            throw new MysqlException(DataCode.DELETE_EXCEPTION);
        }

        map.put("code", DataCode.SUCCESS.getCode());
        map.put("message", DataCode.SUCCESS.getMessage());

        deleteRedisCache();//清空账号查询相关的缓存

        return GsonUtils.toJson(map);
    }

    @Override
    @AutowireUserToken
    public String modifyDealerAccountState(DealerAccount dealerAccount, UserInfoToken userInfoToken) {
        Map<String, Object> map = new HashMap<>();
        // 参数为空
        if (dealerAccount.getList()==null || dealerAccount.getList().size()==0){
            map.put("code", DataCode.PARAM_IS_BLANK.getCode());
            map.put("message", DataCode.PARAM_IS_BLANK.getMessage());
            return GsonUtils.toJson(map);
        }

        dealerAccount.setOptId(userInfoToken.getUserId()); // 只能修改当前运营账号下的经销商总帐号
        dealerAccount.setModifyDate(new Date());

        List<DealerAccount> accounts = null;
        if (dealerAccount.getStatus()==0){
            dealerAccount.setStatus(1);
            accounts = dealerAccountMapper.selectDealerAccountList(dealerAccount);
            dealerAccount.setStatus(0);
        }

        Integer count = dealerAccountMapper.updateDealerAccountInfo(dealerAccount);
        if (count==null || count<=0)
            throw new MysqlException(DataCode.MODIFY_EXCEPTION);
        if (dealerAccount.getStatus()==0 && accounts!=null){
            for (DealerAccount deal: accounts){ // 清空当前redis中登录的账号
                Set<String> keys = redisTemplate.keys(deal.getUserName() + "*");
                if (keys!=null)
                    redisTemplate.delete(keys);
            }
        }

        map.put("code", DataCode.SUCCESS.getCode());
        map.put("message", DataCode.SUCCESS.getMessage());

        deleteRedisCache();//清空账号查询相关的缓存

        return GsonUtils.toJson(map);
    }

    @Override
    public String resetDealerAccountPwd(Integer dealerId) {
        DealerAccount dealerAccount = new DealerAccount();
        dealerAccount.setDealAccountId(dealerId);
        DealerAccount account = dealerAccountMapper.selectDealerAccountOne(dealerAccount);

        if (account==null)
           throw new MysqlException(DataCode.SELECT_EXCEPTION);
        Integer count = dealerAccountMapper.resetDealerAccountPassword(DEALER_DEFAULT_PASSWORD, dealerId);
        if (count==null || count!=1)
            throw new MysqlException(DataCode.MODIFY_EXCEPTION);

        log.debug(account.getUserName()+"*");

        Set<String> keys = redisTemplate.keys(account.getUserName()+"*");
        if (keys!=null)
            redisTemplate.delete(keys);// 删除redis登录的账号

        Map<String, Object> map = new HashMap<>();
        map.put("code", DataCode.SUCCESS.getCode());
        map.put("message", DataCode.SUCCESS.getMessage());

        return GsonUtils.toJson(map);
    }

    @Override
    @AutowireUserToken
    public String modifyDealerAccountInfo(DealerAccount dealerAccount, UserInfoToken userInfoToken) {

        dealerAccount.setModifyDate(new Date());
        dealerAccount.setOptId(userInfoToken.getUserId());
        dealerAccount.setList(Collections.singletonList(dealerAccount.getDealAccountId()));
        dealerAccount.setUserName(null); // 防止用户恶意设置
        dealerAccount.setDealPwd(null); // 防止用户恶意设置
        System.out.println(dealerAccount.getList());

        Integer count = dealerAccountMapper.updateDealerAccountInfo(dealerAccount);
        if (count==null || count<=0)
            throw new MysqlException(DataCode.MODIFY_EXCEPTION);

        Map<String, Object> map = new HashMap<>();
        map.put("code", DataCode.SUCCESS.getCode());
        map.put("message", DataCode.SUCCESS.getMessage());

        deleteRedisCache();//清空账号查询相关的缓存

        return GsonUtils.toJson(map);
    }


    private void deleteRedisCache(){
        Set<String> keys = redisTemplate.keys(CACHE_NAMESPACE + "*");
        if (keys!=null)
            redisTemplate.delete(keys);
    }

}
